<?php
namespace app\api\controller;

use app\common\model as M;

/**
 * 用户模块
 */
class UserAddress extends \app\api\ApiAuth
{
    public $model = '\app\common\model\user\UserAddress';

    /**
     * 退出登录
     * @Author   FW
     * @DateTime 2024-03-13
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function details ($id)
    {
        $details = $this->model::where('id',$id)->find();
        return $this->returnSuccess($details);
    }

    /**
     * 保存地址
     * @Author   FW
     * @DateTime 2024-03-13
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function save()
    {
        $post = $this->request->post();
        $post['uid'] = $this->uid;

        $this->model::startTrans();
        try {
            $isDefault = $post['is_default'] ?? 0;
            // 将用户其它地址设为非默认
            if ( $isDefault == 1 ) {
                $res = $this->model::where('uid' , $this->uid)->update(['is_default' => 0]);
                if ( $res === false ) throw new \Exception('设置默认地址失败');
            }

            $res = $this->model::saveOne($post);
            if ( $res === false ) throw new \Exception('保存地址失败');

            $this->model::commitTrans();
            return $this->returnSuccess();
        } catch (\Exception $e ) {
            $this->model::rollbackTrans();
            return $this->returnFail($e->getMessage());
        }
        $this->model::rollbackTrans();
        return $this->returnFail('保存地址失败');
    }

    public function delAddress ($id)
    {
        $res = $this->model::where('id',$id)->delete();
        return $this->returnSuccess($res);
    }
}//Class End